package com.pdgps;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import com.pdlocation.model.LocationPoint;
import com.pdlocation.service.SingleLocationRequester;
import com.pdlocation.service.TrackingService;
import com.pdlocation.util.BatteryOptimizationUtils;
import com.pdlocation.viewmodel.LocationViewModel;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private static final int PERMISSION_REQUEST_CODE = 1001;

    private Button startButton, stopButton, showMapButton;
    private TextView statusText, locationText;

    private LocationViewModel locationViewModel;

    private static final int REQUEST_IGNORE_BATTERY_OPTIMIZATIONS = 1002;


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 在onActivityResult中检查结果（可选）
        if (requestCode == 1001) {
            if (BatteryOptimizationUtils.isIgnoringBatteryOptimizations(this)) {
                // 用户已成功将应用添加到白名单
                Toast.makeText(this, "用户已成功将应用添加到白名单", Toast.LENGTH_SHORT).show();
            } else {
                // 用户未进行操作或拒绝了设置
                Toast.makeText(this, "用户未进行操作或拒绝了设置", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 检查并请求电池优化豁免
//        checkBatteryOptimization();


        // 在Activity中调用
        BatteryOptimizationUtils.showBatteryOptimizationDialog(this, 1001);
        // 或者直接跳转
        boolean success = BatteryOptimizationUtils.goToBatterySettings(this, 1001);
        if (!success) {
            Toast.makeText(this, "无法打开电池设置页面，请手动设置", Toast.LENGTH_SHORT).show();
        }

        startButton = findViewById(R.id.start_button);
        stopButton = findViewById(R.id.stop_button);
        showMapButton = findViewById(R.id.show_map_button);
        statusText = findViewById(R.id.status_text);
        locationText = findViewById(R.id.location_text);

        startButton.setOnClickListener(v -> startLocationUpdates());
        stopButton.setOnClickListener(v -> stopLocationUpdates());
        showMapButton.setOnClickListener(v -> showMap());

//        // 使用自定义单次定位请求器
//        SingleLocationRequester requester = new SingleLocationRequester(this);
//        requester.requestLocation(new SingleLocationRequester.SingleLocationCallback() {
//            @Override
//            public void onLocationReceived(Location location) {
//                runOnUiThread(() -> {
//                    // 显示位置信息
//                    Toast.makeText(MainActivity.this, "定位成功" + location.getLongitude() + "," + location.getLatitude(), Toast.LENGTH_SHORT).show();
//                });
//            }
//
//            @Override
//            public void onLocationFailed(String errorMessage) {
//                runOnUiThread(() -> {
//                    Toast.makeText(MainActivity.this, "定位失败: " + errorMessage, Toast.LENGTH_SHORT).show();
//                });
//            }
//        });

        // 初始化ViewModel
        locationViewModel = new ViewModelProvider(this).get(LocationViewModel.class);

        // 观察位置更新
        locationViewModel.getData().observe(this, new Observer<LocationPoint>() {
            @Override
            public void onChanged(LocationPoint locationPoint) {
                System.out.println("返回的定位信息：" + locationPoint);
                updateLocationDisplay(locationPoint);
            }
        });

        // 检查定位权限
        if (!checkLocationPermission()) {
            requestLocationPermission();
        } else {
            updateUI();
        }
    }

    private boolean checkLocationPermission() {
        return ContextCompat.checkSelfPermission(
                this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }

    private void requestLocationPermission() {
        ActivityCompat.requestPermissions(
                this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                PERMISSION_REQUEST_CODE
        );
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "定位权限已获取", Toast.LENGTH_SHORT).show();
                updateUI();
            } else {
                Toast.makeText(this, "需要定位权限才能使用此应用", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    private void startLocationUpdates() {
        if (!checkLocationPermission()) {
            requestLocationPermission();
            return;
        }
        if (isLocationServiceRunning()) {
            statusText.setText("定位服务正在运行");
        } else {
            locationViewModel.startTrackingService(this);
            updateUI();
            Toast.makeText(this, "开始跟踪位置", Toast.LENGTH_SHORT).show();
        }
    }

    private void stopLocationUpdates() {
        if (isLocationServiceRunning()) {
            statusText.setText("定位服务正在运行");
            locationViewModel.stopTrackingService(this);
            updateUI();
        } else {
            Toast.makeText(this, "停止跟踪位置", Toast.LENGTH_SHORT).show();
        }


    }

    private void showMap() {
        // 跳转到地图显示界面
        // 此处省略地图实现
        Toast.makeText(this, "地图功能将在后续版本中提供", Toast.LENGTH_SHORT).show();
    }

    private void updateUI() {
        boolean hasPermission = checkLocationPermission();
//        startButton.setEnabled(hasPermission && !isLocationServiceRunning());
//        stopButton.setEnabled(hasPermission && isLocationServiceRunning());

        if (isLocationServiceRunning()) {
            statusText.setText("定位服务正在运行");
        } else {
            statusText.setText("定位服务已停止");
        }
    }

    private boolean isLocationServiceRunning() {
        // 此处简化实现，实际应检查服务是否在运行
        return locationViewModel.isTrackingServiceRunning(TrackingService.class, this);
    }

    private void updateLocationDisplay(LocationPoint location) {
        if (location == null) {
            locationText.setText("未获取到位置信息");
            return;
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        String timeString = dateFormat.format(new Date(location.getTimestamp()));

        StringBuilder sb = new StringBuilder();
        sb.append("纬度: ").append(String.format("%.6f", location.getLatitude())).append("\n");
        sb.append("经度: ").append(String.format("%.6f", location.getLongitude())).append("\n");

        if (location.hasAltitude()) {
            sb.append("海拔: ").append(String.format("%.2f", location.getAltitude())).append(" 米\n");
        }

        sb.append("精度: ").append(String.format("%.2f", location.getAccuracy())).append(" 米\n");
        sb.append("来源: ").append(location.getSourceName());

        if (location.getSource() == 0 || location.getSource() == 2) {
            sb.append(" (").append(location.getSatelliteCount()).append(" 颗卫星)\n");
        } else {
            sb.append("\n");
        }

        sb.append("时间: ").append(timeString);
        sb.append("\n");
        sb.append("位置: ").append(location.getAddress());

        locationText.setText(sb.toString());

        // 根据精度设置文本颜色
        if (location.getAccuracy() < 10) {
            locationText.setTextColor(ContextCompat.getColor(this, R.color.high_accuracy));
        } else if (location.getAccuracy() < 30) {
            locationText.setTextColor(ContextCompat.getColor(this, R.color.medium_accuracy));
        } else {
            locationText.setTextColor(ContextCompat.getColor(this, R.color.low_accuracy));
        }
    }
}